﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace SWebAction
{
    public class DefaultFilterResponse : Stream
    {
        Stream responseStream;
        long position;
        StringBuilder responseHtml;
        bool isWrite = false;

        public DefaultFilterResponse(Stream inputStream)
        {
            responseStream = inputStream;
            responseHtml = new StringBuilder();
        }

        public override bool CanRead
        {
            get
            {
                return responseStream.CanRead;
            }
        }

        public override bool CanSeek
        {
            get
            {
                return responseStream.CanSeek;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return responseStream.CanWrite;
            }
        }

        public override void Flush()
        {
            if (!isWrite)
            {
                //
                byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(responseHtml.ToString());
                responseStream.Write(data, 0, data.Length);
            }
            responseStream.Flush();
        }

        public override long Length
        {
            get
            {
                return responseStream.Length;
            }
        }

        public override long Position
        {
            get
            {
                return position;
            }
            set
            {
                position = value;
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return responseStream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return responseStream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            responseStream.SetLength(value);
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            string strBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);

            //采用正则，检查输入的是否有页面结束符</html>
            Regex eof = new Regex("</html>", RegexOptions.IgnoreCase);

            if (!eof.IsMatch(strBuffer))
            {
                //页面没有输出完毕，继续追加内容
                responseHtml.Append(strBuffer);
            }
            else
            {
                //页面输出已经完毕，截获内容
                responseHtml.Append(strBuffer);
                string finalHtml = responseHtml.ToString();

                //按钮权限控制，返回处理后的html
                //finalHtml = Privilege.Button(finalHtml);
                

                #region 测试时写的代码，可供参考
                //HtmlDocument doc = new HtmlDocument();
                //doc.LoadHtml(finalHtml);
                //HtmlNode hn = doc.DocumentNode;
                ////hn.SelectNodes("//div[@id='KSS_moveBox']")[0];

                ////激发数据已经获取事件
                ////OnRawDataRecordedEvent(this, new RawDataEventArgs(finalHtml));//finalHtml就是源文件内容

                ////继续传递要发出的内容写入流

                //if (MyUrl.ToAb("~/") != "/")
                //{
                //    var Nodes = hn.SelectNodes("//script");
                //    Nodes[0].SetAttributeValue("src", MyUrl.ToAb("~/" + Nodes[0].Attributes["src"].Value));
                //    finalHtml = hn.WriteTo();
                //}
                //var a = hn.SelectNodes("//a[@name='shenheceshi']");
                //foreach (var item in a)
                //{
                //    item.Remove();
                //}
                //finalHtml = hn.WriteTo();
                #endregion

                int iCount = finalHtml.ToLower().LastIndexOf("</html>") + 7;
                byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(finalHtml.Substring(0, iCount));
                isWrite = true;
                responseStream.Write(data, 0, data.Length);
            }
        }
    }
}
